<template>
  <div v-if='instanceId'>
    <br />
    <el-card>
      <template #header>
        <div class="card-box-header">
          <span>流程状态</span>
          <div v-if="show1" @click="show1 = !show1" class="header-btn">
            收起
            <i class="el-icon-arrow-down"></i>
          </div>
          <div v-else @click="show1 = !show1" class="header-btn">
            展开
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
      </template>
      <div v-if="steps && steps.length">
        <el-collapse-transition>
          <status-info
            :currentStep="currentStep"
            :steps="steps"
            :isSkip="isSkipYs"
          />
        </el-collapse-transition>
      </div>
    </el-card>
    <br />

    <el-card>
      <template #header>
        <div class="card-box-header">
          <span>流转记录</span>
          <div v-if="show2" @click="show2 = !show2" class="header-btn">
            收起
            <i class="el-icon-arrow-down"></i>
          </div>
          <div v-else @click="show2 = !show2" class="header-btn">
            展开
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
      </template>
      <div v-show="show2">
        <el-collapse-transition>
          <approval-info :activities="approveRecord" />
        </el-collapse-transition>
      </div>
    </el-card>
  </div>

  <approveDialog
    v-if="approveDialogVisiable"
    :nodeId="nodeId"
    :flowType="model.flowType"
    @cancel="cancel"
    @sure="sureSubmit"
  ></approveDialog>
</template>

<script lang="ts" setup>
import { ref, reactive,defineExpose } from "vue";
import { useRouter, useRoute } from "vue-router";
import approveDialog from "/@/components/approveDialog/index.vue";
import StatusInfo from "/@/components/StatusInfo/index.vue";
import ApprovalInfo from "/@/components/ApprovalInfo/index.vue";
import { flowStatusObj } from "/@/components/StatusInfo/type";
import {
  flowStart,
  getApproveHistory,
  flowSubmit
} from "/@/api/project";
import {
  getScientificInfo
} from "/@/api/scientific";
import NotifMessage from "/@/utils/message/notification";
import { storageLocal } from "/@/utils/storage"
const router = useRouter();
const route = useRoute();
let show1 = ref<boolean>(true);
let show2 = ref<boolean>(true);
let approveDialogVisiable = ref<boolean>(false); // 点击提交弹窗，选择下一步审批人
const isSkipYs = route.query.isSkipYs;
const currentStep = ref(null);
const steps = ref([]);
const approveRecord = ref([]);
const model = reactive({
  docid: window["ecmDocType"].project,
  flowType: "2029",
  approveHandlerId: null,
  dialogType: "approval",
  saveLoading: false,
  dialogFormVisible: false,
  kyTypes: {
    51: "专利" ,
    52: "论文",
    53: "专著",
    54: "标准" ,
    55: "科技奖励",
    56: "科技制度建设",
    57: "软件著作" ,
    58: "其他"
  },
});
const nodeId = ref(route.query.nodeId || "ACT_010");
const flowId = ref(route.query.flowId || "");
const instanceId = ref(route.query.instanceId || "");
const rdScientificId = ref(route.query.rdScientificId || "");
const taskId = ref(route.query.taskId || "");
//发起流程
const flowStartData = reactive({
  formBaseInfo: {
    billName: "",
    projectName: "",
    projectManageId: "",
    id: "",
    flowStartAttachmentArr: []
  },
  flowFormData: {
    businessId: "",
    flowTypeCode: "2029",
    nodeId: nodeId,
    projectManageId: "",
    remarks: "",
    saveState: "1"
  },
  formSubMap: {
    stageStatus: "51",
    flowType: "2029",
    assignee: null,
    opinion: ""
  }
});

const flowPassData = reactive({
  formBaseInfo: {
    id:rdScientificId,
    acceptUsers: null
  },
  flowFormData: {
    approvalComments: "",
    approvalResult: "",
    businessId: rdScientificId,
    flowId: flowId,
    flowTypeCode: "2029",
    instanceId: instanceId,
    nodeId: nodeId,
    remarks: "",
    saveState: "1"
  },
  formSubMap: {
    stageStatus: "51",
    flowType: "2029",
    nodeId: nodeId,
    procInstId: instanceId,
    taskId: taskId,
    opinion: "",
    assignee: null,
    isChargehand: "1", //1：向下提交到下一步：0：回退到某一步
    specialReject: "0"
  },
  tmpStorage: {
    nodeId:nodeId,
    flowId:flowId,
    taskId:taskId,
    handlerId: null,
    valueJson: ""
  }
});

//点击提交，校验通过后，弹窗：选择下一节点处理人
const handleSubmit = async (businessId,item,type) => {
  approveDialogVisiable.value = true;
  flowStartData.formSubMap.stageStatus = type;
  flowStartData.formBaseInfo.id = businessId;
  flowStartData.formBaseInfo.billName = `${model.kyTypes[type]}-${item.name}-审批流程`;
  flowStartData.formBaseInfo.projectName = item.projectName ? item.projectName : ""
  flowStartData.formBaseInfo.projectManageId = item.projectId ? item.projectId : businessId;
  flowStartData.flowFormData.projectManageId = item.projectId ? item.projectId : businessId;
  flowStartData.flowFormData.businessId = businessId;
};

//驳回后重新发起流程
const approvalSubmit = async (type) => {
  approveDialogVisiable.value = true;
  flowPassData.formSubMap.stageStatus = type;
};

const sureSubmit = async params => {
  approveDialogVisiable.value = false;
  model.saveLoading = true;
  if (route.query.instanceId) {//驳回到第一步，重新提交审批
    flowPassSubmit(params);
  } else {
    flowSumbitStart(params);
  }
};

// 流程发起
const flowSumbitStart = async params => {
  flowStartData.flowFormData.remarks = params.remark;
  flowStartData.formSubMap.assignee = params?.handlederId?.id;
  flowStartData.formSubMap.opinion = `备注:${params.remark}`;
  model.saveLoading = true;
  const { code, message } = await flowStart(flowStartData);
  if (code === 200) {
    NotifMessage.success(message);
    goBack();
  } else {
    NotifMessage.error(message);
  }
};

// 流程提交
const flowPassSubmit = async params => {
  flowPassData.flowFormData.approvalComments = params.remark;
  flowPassData.flowFormData.approvalResult = "1"; //同意：1，不同意：0
  flowPassData.flowFormData.remarks = params.remark;
  flowPassData.flowFormData.flowTypeCode = model.flowType;
  flowPassData.formSubMap.opinion = ``;
  flowPassData.tmpStorage.valueJson = JSON.stringify(flowPassData.formSubMap);
  const info = storageLocal.getItem("rdms-info");
  const userId = info?.userId;
  flowPassData.tmpStorage.handlerId = userId;
  flowPassData.formBaseInfo.acceptUsers = params?.handlederId?.id || userId;
  flowPassData.formSubMap.assignee = params?.handlederId?.id || userId;
  flowPassData.formSubMap.isChargehand = "1";
  flowPassData.formSubMap.flowType = model.flowType;
  const { code, message } = await flowSubmit(flowPassData);
  if (code === 200) {
    NotifMessage.success(message);
    goBack();
  } else {
    NotifMessage.error(message);
  }
};

//查询审批信息详情
const initScientificInfo = async () => {
  try {
    const { code, data } = rdScientificId.value && (await getScientificInfo(rdScientificId.value));
    if (code === 200) {
      flowId.value = data.flowId;
      instanceId.value = data.instanceId;
      nodeId.value = data?.nodeStatusCode
      rdScientificId.value = data.id
      getApproveHistoryList()
      getStep();
    }
  } catch (err) {
    console.log(err);
  }
};

//获取流程转态
const getStep = () => {
  steps.value = flowStatusObj[model.flowType];
  if (steps.value && steps.value.length) {
    steps.value.forEach((item, index) => {
      if (item.nodeId === nodeId.value) {
        currentStep.value = Number(index);
      }
    });
  }
};

//查询流程审批记录
const getApproveHistoryList = async () => {
  if (instanceId.value) {
    const { code, data } = await getApproveHistory(instanceId.value);
    if (code === 200) {
      approveRecord.value = data;
    }
  }
};

const cancel = async () => {
  approveDialogVisiable.value = false;
  model.saveLoading = false;
};

const goBack = (): void => {
  router.push("/document/scientific?activeName=1");
};
initScientificInfo();
defineExpose({
  handleSubmit,
  approvalSubmit
});
</script>

<style lang="scss" scoped>
.empt-content {
  height: calc(100vh - 200px);
  width: 100%;
}

.card-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-box-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-btn {
    font-size: 14px;
    cursor: pointer;
  }
}
</style>
